import React from 'react'
import {
  Form,
  Input,
  Select,
  Button,
  Table,
  Radio,
  DatePicker,
  Row,
  Col,
  Card
} from 'antd'
import _ from 'lodash'
import moment from 'moment'
import { connect } from 'react-redux'
import {
  projectFindBypageApi,
  histaskFindTaskStaticInfoApi,
  histaskFindTaskInfoApi
} from '../../api/ajax'
import ExcelFile from 'react-data-export'
import { ExcelSheet, ExcelColumn } from 'react-data-export'

const FormItem = Form.Item
const Option = Select.Option
const RadioGroup = Radio.Group
const { RangePicker } = DatePicker

const toZero = str => {
  if (!str) {
    return '0'
  }
  return str.toString()
}

const columns = [
  {
    title: '任务编号',
    dataIndex: 'taskCode',
    width: 150
  },
  {
    title: '项目名称',
    dataIndex: 'projectName'
  },
  {
    title: '项目单位',
    dataIndex: 'branch'
  },
  {
    title: '源产品名称',
    dataIndex: 'productName'
  },
  {
    title: '目标名称',
    dataIndex: 'userName'
  },
  {
    title: '发送文件（个）',
    dataIndex: 'fileNum'
  },
  {
    title: '源产品故障（次）',
    dataIndex: 'numSour'
  },
  {
    title: '目标故障（次）',
    dataIndex: 'numUser'
  }
]

class Analysis extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      filterTimeSelect: true,
      projectSource: [],
      taskInfo: {},
      dataSource: []
    }
  }
  componentDidMount() {
    this.loadData()
    this.reflashTimer = setInterval(() => {
      this.loadData()
    }, 5000)
  }
  componentWillUnmount() {
    clearInterval(this.reflashTimer)
  }
  loadData = () => {
    const { getFieldsValue } = this.props.form
    const value = getFieldsValue()
    projectFindBypageApi().then(v => {
      this.setState({
        projectSource: _.isNil(v.list.results) ? [] : v.list.results
      })
    })
    histaskFindTaskInfoApi().then(v => {
      this.setState({ taskInfo: v })
    })
    _.each(value, (v, k) => {
      if (_.isNil(v)) value[k] = ''
    })
    if (value.dateType === 'custom') {
      if (value.timeRange === '') {
        value.startDate = moment('1950-01-01')
        value.endDate = moment('9999-12-01')
      } else {
        value.startDate = value.timeRange[0]
        value.endDate = value.timeRange[1]
      }
    }
    histaskFindTaskStaticInfoApi(value).then(v => {
      this.setState({ dataSource: v })
    })
  }
  render() {
    const { getFieldDecorator, resetFields } = this.props.form
    const { filterTimeSelect, projectSource, taskInfo, dataSource } = this.state
    return (
      <div className="home">
        <div className="home-head" style={{ paddingTop: 0 }}>
          <div>
            <h3>任务概况</h3>
            <Row gutter={16}>
              <Col span={8}>
                <Card title="任务统计">
                  <div>
                    总任务数：
                    <span
                      className="font-blod-large"
                      style={{ color: '#FFD86E' }}
                    >
                      {taskInfo.allTaskNum}
                    </span>
                  </div>
                  <div>
                    本周正常运行：
                    <span
                      className="font-blod-large"
                      style={{ color: '#FFD86E' }}
                    >
                      {taskInfo.weekTaskNum}
                    </span>
                  </div>
                </Card>
              </Col>
              <Col span={8}>
                <Card title="文件传输统计">
                  <div>
                    传输文件总数：
                    <span
                      className="font-blod-large"
                      style={{ color: '#49A9EE' }}
                    >
                      {taskInfo.allTaskFileNum}
                    </span>
                  </div>
                  <div>
                    本周传输：
                    <span
                      className="font-blod-large"
                      style={{ color: '#49A9EE' }}
                    >
                      {taskInfo.weekTaskFileNum}
                    </span>
                  </div>
                </Card>
              </Col>
              <Col span={8}>
                <Card title="故障统计">
                  <div>
                    总共发生故障（次）：
                    <span
                      className="font-blod-large"
                      style={{ color: '#F3857C' }}
                    >
                      {taskInfo.allTaskProblemNum}
                    </span>
                  </div>
                  <div>
                    本周发生：
                    <span
                      className="font-blod-large"
                      style={{ color: '#F3857C' }}
                    >
                      {taskInfo.weekTaskProblemNum}
                    </span>
                  </div>
                </Card>
              </Col>
            </Row>
          </div>
          <h3 style={{ marginTop: '10px' }}>任务报表</h3>
          <Form layout="inline">
            <div>
              <FormItem label="筛选时间">
                {getFieldDecorator('dateType')(
                  <RadioGroup
                    onChange={v => {
                      v.target.value === 'custom'
                        ? this.setState({ filterTimeSelect: false })
                        : this.setState({ filterTimeSelect: true })
                    }}
                  >
                    <Radio value={'week'}>本周</Radio>
                    <Radio value={'mon'}>本月</Radio>
                    <Radio value={'quart'}>本季度</Radio>
                    <Radio value={'year'}>本年</Radio>
                    <Radio value={'custom'}>自定义</Radio>
                  </RadioGroup>
                )}
              </FormItem>
              {!filterTimeSelect && (
                <FormItem>
                  {getFieldDecorator('timeRange')(
                    <RangePicker placeholder="请选择" />
                  )}
                </FormItem>
              )}
            </div>
            <FormItem label="源产品名称">
              {getFieldDecorator('productName')(<Input />)}
            </FormItem>
            <FormItem label="目标名称">
              {getFieldDecorator('userName')(<Input />)}
            </FormItem>
            <FormItem label="项目名称">
              {getFieldDecorator('projectId')(
                <Select placeholder="请选择" style={{ width: 170 }}>
                  {projectSource.map(v => (
                    <Option key={v.id} value={v.id}>
                      {v.projectName}
                    </Option>
                  ))}
                </Select>
              )}
            </FormItem>
            <FormItem label="项目单位">
              {getFieldDecorator('branch')(<Input />)}
            </FormItem>
            <Button
              type="primary"
              style={{ marginRight: '10px' }}
              onClick={() => this.loadData()}
            >
              查询
            </Button>
            <Button
              onClick={() => {
                resetFields()
                this.setState({ filterTimeSelect: true }, () =>
                  this.loadData(1)
                )
              }}
            >
              重置
            </Button>
            <ExcelFile
              filename={'统计分析.xlsx'}
              element={
                <Button type="primary" style={{ marginLeft: '20px' }}>
                  导出Excel
                </Button>
              }
            >
              <ExcelSheet data={dataSource} name="analysis">
                <ExcelColumn label="任务编号" value="taskCode" />
                <ExcelColumn label="项目名称" value="projectName" />
                <ExcelColumn label="单位名称" value="branch" />
                <ExcelColumn label="源产品名称" value="productName" />
                <ExcelColumn label="目标" value="userName" />
                <ExcelColumn
                  label="发送文件（个）"
                  value={({ fileNum }) => toZero(fileNum)}
                />
                <ExcelColumn
                  label="源产品故障（次）"
                  value={({ numSour }) => toZero(numSour)}
                />
                <ExcelColumn
                  label="目标故障（次）"
                  value={({ numUser }) => toZero(numUser)}
                />
              </ExcelSheet>
            </ExcelFile>
          </Form>
        </div>
        <div>
          <Table
            dataSource={dataSource}
            scroll={{ x: 1200 }}
            columns={columns}
            rowKey={'taskCode'}
          />
        </div>
      </div>
    )
  }
}

export default connect(state => ({
  state
}))(Form.create()(Analysis))
